package cn.xiaobai.v1;

import cn.xiaobai.http.ResponseHeader;
import cn.xiaobai.utils.LoggerFactory;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 第一版
 * 创建 ServerSocket 服务, 监听一个端口, 如果客户端连接该端口,则建立连接, 返回socket 对象
 *
 * @Author yangdaji
 * @Date 2023/11/29
 * @PackageName cn.xiaobai.v1
 * @ClassName Tomcat
 */
public class HttpHandler1 {


    static LoggerFactory.Logger log = LoggerFactory.getLogger(HttpHandler1.class);

    private String body;

    public void start() throws IOException {
        // 1. 创建 ServerSocket, 并绑定 8080 端口, 使用默认ip 0.0.0.0 (允许任何ip)
        int port = 8080;
        ServerSocket serverSocket = new ServerSocket(port);
        log.info("====== tomcat v1 监听 {} 端口", port);
        // 如果服务没有关闭则一直监听
        while (!serverSocket.isClosed()) {
            // 接收请求
            Socket socket = serverSocket.accept();

            // 接收到发送的数据
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            // 2.读取数据
            String msg = "";
            log.info("开始接收数据");
            while ((msg = bufferedReader.readLine()) != null) {
                if (msg.length() == 0) {
                    break;
                }
                log.info("接收到客户端请求数据: {}", msg);
            }

            log.info("响应客户端数据");
            // 3. 响应数据
            OutputStream outputStream = socket.getOutputStream();
            // 构建响应体, 返回给客户端
            // 响应头
//            String respHeader = "HTTP/1.1 200 OK\r\n" +
//                    "Content-Type: text/html;charset=utf-8\r\n\r\n";

            ResponseHeader responseHeader = new ResponseHeader(200);
            log.info("请求头信息: {}", responseHeader);

            String response = responseHeader + body;
            outputStream.write(response.getBytes());

            // 关闭资源
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            socket.close();
        }
    }


    public void setBody(String body) {
        this.body = body;
    }
}
